import * as vscode from 'vscode';
import { exec, execSync } from 'child_process';

export function activate(context: vscode.ExtensionContext) {
  const disposable = vscode.commands.registerCommand(
    'gerrit-push-helper.pushCode',
    async () => {
      if (!vscode.workspace.workspaceFolders) {
        vscode.window.showErrorMessage('没有打开的工作区，请先打开一个工作区');
      }
      const workspaceFolder = vscode.workspace.workspaceFolders?.[0].uri.fsPath;
      try {
        const isGitRepo = execSync('git rev-parse --is-inside-work-tree', {
          cwd: workspaceFolder,
        })
          .toString()
          .trim();
        if (isGitRepo !== 'true') {
          vscode.window.showErrorMessage(
            '当前目录不是一个 git 仓库，请在 git 仓库中使用此命令'
          );
          return;
        }
      } catch (err) {
        vscode.window.showErrorMessage(
          '当前目录不是一个 git 仓库，请在 git 仓库中使用此命令'
        );
        return;
      }

      const config = vscode.workspace.getConfiguration('gerritPushHelper');
      const reviewers: string[] = config.get('reviewers', []);
      if (reviewers.length === 0) {
        vscode.window.showErrorMessage(
          '请先在[gerritPushHelper]设置中配置 reviewer 列表。'
        );
        return;
      }
      let reviewer: string;
      if (reviewers.length === 1) {
        reviewer = reviewers[0];
      } else {
        reviewer =
          (await vscode.window.showQuickPick(reviewers, {
            placeHolder: '请选择一个 reviewer',
          })) || '';
      }
      if (!reviewer) {
        vscode.window.showErrorMessage('未选择 reviewer，取消代码推送！');
        return;
      }

      vscode.window.withProgress(
        {
          location: vscode.ProgressLocation.Notification,
          title: '正在推送代码',
          cancellable: false,
        },
        (process) => {
          return new Promise((resolve, reject) => {
            process.report({ message: '正在获取当前分支...' });
            exec(
              'git symbolic-ref --short HEAD',
              { cwd: workspaceFolder },
              (err, stdout) => {
                if (err) {
                  vscode.window.showErrorMessage(
                    '获取当前分支失败',
                    err.message
                  );
                  reject(err);
                  return;
                }

                const currentBranch = stdout.trim();
                process.report({ message: `当前分支: ${currentBranch}` });
                const command = `git push origin HEAD:refs/for/${currentBranch}%r=${reviewer}`;
                process.report({
                  message: `正在推送 ${currentBranch} 分支代码...`,
                });

                exec(command, { cwd: workspaceFolder }, (err, stdout) => {
                  if (err) {
                    if (err.message.includes('no new changes')) {
                      vscode.window.showInformationMessage(
                        `${currentBranch} 分支推送成功: 没有新的提交需要推送`
                      );
                      resolve(stdout);
                      return;
                    }
                    vscode.window.showErrorMessage(`推送失败 ${err.message}`);
                    reject(err);
                  } else {
                    vscode.window.showInformationMessage(
                      `${currentBranch} 分支推送成功(reviewer: ${reviewer})`
                    );
                    resolve(stdout);
                  }
                });
              }
            );
          });
        }
      );
    }
  );

  context.subscriptions.push(disposable);
}

export function deactivate() {}
